﻿using System;
using FunctionalCLR.Core;
using Zove.Runtime;
using Zove.Runtime.FunctionalCLR;

namespace Zove.Shell.Core {
    public class FactorUnaryFunctionTranslator
        : CSharpCodeTranslator {

        private string subject = string.Empty;

        public FactorUnaryFunctionTranslator(
            IFunctionManager funMgr, string subject)
            : base(funMgr) {
            this.subject = subject;
        }

        #region IZoveNumericsVisitor Members

        public override object Visit(IdentifierNode node) {
            FactorNode fn = node as FactorNode;

            string name = fn.Factor.Name;
            if (fn.Factor == null) {
                throw new ArgumentException("Factor is null");
            } else if (fn.Factor.ParentModel != null
                && fn.Factor.ParentModel.Solution.Name != null) {
                name = fn.Factor.ParentModel.Solution.Name + "." + fn.Factor.Name;
            }
            if (this.subject == name) {
                return "x";
            }

            if (fn.Factor.Status != RuntimeFactorStatus.Unknown) {
                return fn.Factor.Value;
            }

            throw new Exception(
                string.Format(
                "Factor {0} must be specified.", fn.Factor.Name));
        }

        #endregion
    }
}
